﻿using Elastic.Clients.Elasticsearch;
using Elastic.Transport;
using Elasticsearch.Configuration;
using Elasticsearch.Model;
using Elasticsearch.Service;
using Microsoft.Extensions.Options;

namespace Elasticsearch.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Elasticsearch服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddElasticsearchServices(this IServiceCollection services, IConfiguration configuration)
        {
            // 配置Elasticsearch
            services.Configure<ElasticsearchConfig>(configuration.GetSection("Elasticsearch"));

            // 注册Elasticsearch客户端
            services.AddSingleton<ElasticsearchClient>(provider =>
            {
                var config = provider.GetRequiredService<IOptions<ElasticsearchConfig>>().Value;
                //var logger = provider.GetRequiredService<ILogger<ElasticsearchClient>>();
                //es集群连接配置
                var nodes = config.Nodes.Select(n => new Uri(n)).ToList();
                var pool = new StaticNodePool(nodes);
                //配置集群连接
                var settings = new ElasticsearchClientSettings(pool)
                      .ServerCertificateValidationCallback((sender, cert, chain, errors) => true) // 忽略 TLS 证书验证 // 关闭产品检查() // 关闭产品检查
                    .RequestTimeout(TimeSpan.FromSeconds(config.RequestTimeoutSeconds)) ;

                // 如果配置了用户名和密码，添加认证
                if (!string.IsNullOrEmpty(config.Username) && !string.IsNullOrEmpty(config.Password))
                {
                    settings.Authentication(new BasicAuthentication(config.Username, config.Password));
                }

                // 如果启用调试模式，添加调试日志
                if (config.EnableDebug)
                {
                    settings.EnableDebugMode();
                }

                return new ElasticsearchClient(settings);
            });

            return services;
        }
    }
}
